import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingDeque;
import java.util.concurrent.BlockingQueue;

//   写一个普通的线程池
class MyTreadPool {
    private BlockingQueue<Runnable> queue = new ArrayBlockingQueue<>(1000);
    private int maxPoolSize = 0;
    private List<Thread> threadList = new ArrayList<>();   //用链表来存储一下线程

    //初始化线程池
    public MyTreadPool(int corePoolSize,int maxPoolSize) {
        this.maxPoolSize = maxPoolSize;

        //创建若干个线程   核心线程
        for (int i = 0; i < corePoolSize; i++) {
            Thread t = new Thread(() -> {
                try {
                    while (true) {
                        Runnable runnable = queue.take();
                        runnable.run();
                    }
                }catch (InterruptedException e) {
                    e.printStackTrace();
                }
            });
            t.start();
            threadList.add(t);
        }
    }

    //把任务添加到线程池中   submit方法
    void submit (Runnable runnable) throws InterruptedException {
        //如果现在任务比较长   说明已有的线程不足以处理这些任务  得新建线程
        queue.put(runnable);

        if (queue.size() >= 500 && threadList.size() < maxPoolSize) {
            //创建新的线程
            Thread t = new Thread(() -> {
                try {
                    while (true) {
                        Runnable task = queue.take();
                        task.run();
                    }
                }catch (InterruptedException e) {
                    e.printStackTrace();
                }
            });
            t.start();
        }
    }
}

public class Text {
    public static void main(String[] args) throws InterruptedException {
        //实例化一个线程池对象
        MyTreadPool myTreadPool = new MyTreadPool(10,20);
        for (int i = 0; i < 10000; i++) {
            int id = i;
            myTreadPool.submit(new Runnable() {
                @Override
                public void run() {
                    System.out.println("hello" + id +"," +Thread.currentThread().getName());
                }
            });
        }
    }
}
